package beavers.studio.utilities.threads;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import beavers.studio.golfberry.FileManager;
import beavers.studio.golfberry.screens.PictureScreen;
import beavers.studio.utilities.Utils;
import beavers.studio.utilities.callbacks.WebDataCallback;

public class PictureDownloadThread extends Thread implements WebDataCallback {
	//Thread attributes
	PictureScreen 	m_PictureScreen;
	byte[] 			m_BufferImage;
	String[]		m_Urls;
	
	//Thread constructor
	public PictureDownloadThread(PictureScreen pictureScreen, String[] urls) {
		m_PictureScreen = pictureScreen;
		m_BufferImage = null;
		m_Urls = urls;
		
		//Set flag
		PictureScreen.m_Run = true;
	}
	
	public void run() {		
		//Check existing image
		int length = m_Urls.length;
		
		//Download and display remaining image
		for (int i=0;i<length;i++) {
			//Download image if needed
			if (m_Urls[i]!=null) {
				//Download
				Utils.getWebData("http://localhost/golfberry/" + m_Urls[i], this);
				
				//Sleep until download finished
				while (m_BufferImage==null) {		
					try {
						sleep(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				
				//Add display event to queue
				int index = m_Urls[i].lastIndexOf('/');
				final String m_Path = (index!=-1) ? m_Urls[i].substring(index) : m_Urls[i];
				UiApplication.getUiApplication().invokeAndWait(new Runnable() { 
		            public void run() { 
		            	System.out.println(m_Path);
		            	//Save to file
		            	boolean m_Success = FileManager.inst().saveImage(m_BufferImage, m_Path);
		            	System.out.println("SAVE " + m_Success);
		            	//Display
		            	if (m_Success) m_PictureScreen.add(new BitmapField(Bitmap.createBitmapFromBytes(m_BufferImage, 0, m_BufferImage.length, 1)));
		            } 
		        });
				
				//Reset
				m_BufferImage = null;
			}
		}
		
		//Reset flag
		PictureScreen.m_Run = false;
	}

	public void callback(byte[] encodedImage) {
		System.out.println("Image callback received.");
		
		//Act accordingly
		if (encodedImage!=null) m_BufferImage = encodedImage;
	}
}
